package com.excalibur.core.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESAlgorithm {

	/**
	 * 生成AES密钥，生成的密钥用BASE64编码
	 * 128位(256位可能不支持)
	 * @see <a href="http://www.javamex.com/tutorials/cryptography/key_size.shtml">key size</a>
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getKey() throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128); // 192 and 256 bits may not be available
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		return Base64.encodeBase64String(raw);
	}

	/**
	 * AES加密，加密成字节流
	 * 
	 * @param content 需要加密的字符串
	 * @param key BASE64编码密钥
	 * @return
	 * @throws Exception
	 */
	public static byte[] encode(String content, String key) throws Exception {
		byte[] raw = Base64.decodeBase64(key);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
		return encrypted;
	}

	/**
	 * AES加密，加密成Base64字节流
	 * 
	 * @param content 需要加密的字符串
	 * @param key BASE64编码密钥
	 * @return
	 * @throws Exception
	 */
	public static String encodeBase64(String content, String key) throws Exception {
		byte[] encrypted = encode(content, key);
		return Base64.encodeBase64String(encrypted);
	}

	/**
	 * AES解密，解密成字符串
	 * 
	 * @param stream 需要解密的字节流
	 * @param key BASE64编码密钥
	 * @return
	 * @throws Exception
	 */
	public static String decode(byte[] stream, String key) throws Exception {
		byte[] raw = Base64.decodeBase64(key);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] original = cipher.doFinal(stream);
		String originalString = new String(original, "UTF-8");
		return originalString;
	}
}
